package com.huazai.FirstWebApplication;

import com.huazai.Util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "oneServlet", value = "/servlet")
public class OneServlet extends HttpServlet {

    public static void main(String[] args) {
        OneServlet oneServlet = new OneServlet();
        System.out.println("chulai le ");
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("You had do Get");

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.print("<h1>HELLO 你好 servlet</h1>");
        pw.print("<h1>online jdbc test ...</h1>");

        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;


        try {
            conn = DBUtil.ConnectDB();
            String sql = "select * from userinfo";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            pw.print("<table align=\"center\" border=\"1\">");
            pw.print("<tr>" +
                        "<th>用户姓名</th>" +
                        "<th>用户ID</th>" +
                        "<th>用户密码</th>" +
                    "</tr>");
            while( rs.next() ) {
                String pre = rs.getString(1) + "  " + rs.getString(2) + "  " + rs.getString(3);
                pw.print("<tr>");
                pw.print("<td>" + rs.getString(1) + "</td>");
                pw.print("<td>" + rs.getString(2) + "</td>");
                pw.print("<td>" + rs.getString(3) + "</td>");
                pw.print("</tr>");
            }
            pw.print("</table>");

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

    }

}